import 'package:date_format/date_format.dart';
import 'package:flutter/material.dart';
import 'package:flutter_cupertino_date_picker/flutter_cupertino_date_picker.dart';
import 'package:flutter_member/model/StudentSignIn.dart';
import 'package:flutter_member/widget/calendarshow/flutter_clean_calendar.dart';
import 'package:flutter_member/widget/my_appbar.dart';
import 'package:flutter_screenutil/screenutil.dart';
import 'package:parse_server_sdk/parse_server_sdk.dart';
import 'package:collection/collection.dart';

///  出勤记录
class AttendanceRecordPage extends StatefulWidget {
  @override
  _AttendanceRecordPageState createState() => _AttendanceRecordPageState();
}

 String MIN_DATETIME = '2019-05-17';
 String MAX_DATETIME = formatDate(DateTime.now(), [yyyy,'-',mm,'-',dd]);
class _AttendanceRecordPageState extends State<AttendanceRecordPage> {

  //獲取當前日期
  DateTime _nowDate = DateTime.now();

  //用戶名稱
  var _username = '學生1';
  StudentSignIn _signIn;

  String dateTime = formatDate(DateTime.now(), [yyyy, '年', mm, '月']);
  DateTime _dateTime;
  bool _showTitle = true;
  String _format = 'yyyy-MMMM';
  DateTimePickerLocale _locale = DateTimePickerLocale.zh_cn;

  /// 出勤紀錄
  List<dynamic> listAttendance = [];

  /// 第二次保存出勤紀錄
  Map _events = {
    DateTime.parse("2020-11-01"): [
      {
        "objectId": "ETK383Hp0L",
        "checkInAt": "2020-11-10 09:44:00.000Z",
        "date": "2020-11-05",
        "state": "leaved",
        "checkOutAt": "2020-11-10 09:56:00.000Z",
        "createdAt": "2020-11-10 05:50:32.613Z",
        "isDone": true
      }
    ],
    DateTime.parse("2020-11-02"): [
      {
        "objectId": "ETK383Hp0L",
        "checkInAt": "2020-11-10 09:44:00.000Z",
        "date": "2020-11-05",
        "state": "leaved",
        "checkOutAt": "2020-11-10 09:56:00.000Z",
        "createdAt": "2020-11-10 05:50:32.613Z",
        "isDone": true
      }
    ],
    DateTime.parse("2020-11-03"): [
      {
        "objectId": "ETK383Hp0L",
        "checkInAt": "2020-11-10 09:44:00.000Z",
        "date": "2020-11-05",
        "state": "leaved",
        "checkOutAt": "2020-11-10 09:56:00.000Z",
        "createdAt": "2020-11-10 05:50:32.613Z",
        "isDone": true
      }
    ],
    DateTime.parse("2020-11-04"): [
      {
        "objectId": "ETK383Hp0L",
        "checkInAt": "2020-11-10 09:44:00.000Z",
        "date": "2020-11-05",
        "state": "leaved",
        "checkOutAt": "2020-11-10 09:56:00.000Z",
        "createdAt": "2020-11-10 05:50:32.613Z",
        "isDone": true
      }
    ],
    DateTime.parse("2020-11-15"): [
      {
        "objectId": "ETK383Hp0L",
        "checkInAt": "2020-11-10 09:44:00.000Z",
        "date": "2020-11-05",
        "state": "leaved",
        "checkOutAt": "2020-11-10 09:56:00.000Z",
        "createdAt": "2020-11-10 05:50:32.613Z",
        "isDone": true
      }
    ],
    DateTime.parse("2020-11-16"): [
      {
        "objectId": "ETK383Hp0L",
        "checkInAt": "2020-11-10 09:44:00.000Z",
        "date": "2020-11-05",
        "state": "leaved",
        "checkOutAt": "2020-11-10 09:56:00.000Z",
        "createdAt": "2020-11-10 05:50:32.613Z",
        "isDone": true
      }
    ],
  };

  @override
  void initState() {
    super.initState();
    _getStudentSignIn();
    _getAllStudentSignIn();
  }

  Map stuStatus = {};

  Future<void> _getStudentSignIn() async {
    //查詢學生ID
    final ParseUser user = await ParseUser.currentUser() as ParseUser;
    QueryBuilder<ParseObject> query =
    QueryBuilder<ParseObject>(ParseObject('_User'))
      ..whereEqualTo('objectId', user.objectId)
      ..includeObject(['member.student']);
    var apiRes = await query.query();

    QueryBuilder<ParseObject> queryPost =
    QueryBuilder<ParseObject>(ParseObject('Student'))
      ..whereEqualTo('objectId',
          apiRes.results.first['member']['student']['objectId']);

    QueryBuilder queryBuilder =
    QueryBuilder<ParseObject>(ParseObject('StudentSignIn'))
      ..whereMatchesQuery('student', queryPost)
      ..whereLessThan('date', _selectedDay.add(Duration(days: 1)))
      ..whereGreaterThan('date', _selectedDay.subtract(Duration(days: 1)));
    //..setLimit(1);
    print('條件前一天日期：${_selectedDay.subtract(Duration(days: 1))}');
    print('條件後一天日期：${_selectedDay.add(Duration(days: 1))}');
    var res = await queryBuilder.query();
    if (res.success && res.results != null) {
      setState(() {
        _signIn = null;
        _signIn = StudentSignIn(
            res.results.first['objectId'] != null
                ? res.results.first['objectId']
                : null,
            res.results.first['checkInAt'] != null
                ? res.results.first['checkInAt']
                : null,
            res.results.first['checkOutAt'] != null
                ? res.results.first['checkOutAt']
                : null,
            res.results.first['state'] != null
                ? res.results.first['state']
                : null);
      });
    } else {
      print("空数据");
    }
  }

  Future<void> _getAllStudentSignIn() async {
    final ParseUser user = await ParseUser.currentUser();
    var queryMember = QueryBuilder(ParseObject("Member"))
      ..whereEqualTo("objectId", user.get("member")['objectId'])
      ..includeObject(['student']);
    var repMember = await queryMember.query();
    if (repMember.results != null &&
        repMember.success &&
        repMember.results.first['student'] != null) {
      var querySignIn = QueryBuilder(ParseObject("StudentSignIn"))
        ..whereEqualTo("student", repMember.results.first["student"]);
      var repSignIn = await querySignIn.query();
      if (repSignIn.success && repSignIn.results != null) {
        setState(() {
          listAttendance = repSignIn.results
              .map((e) => {
            "objectId": e['objectId'],
            "checkInAt": e['checkInAt'],
            "date": formatDate(e['date'].toLocal(), [yyyy, '-', mm, '-', dd]),
            "state": e['state'],
            "checkOutAt": e['checkOutAt'],
            "createdAt": e['createdAt'],
            "isDone": true
          })
              .toList();
          _events = groupBy(listAttendance, (obj) => obj['date']);
          print(_events);
        });
      }
    }
  }

  List _selectedEvents;
  DateTime _selectedDay = DateTime.now();

  final GlobalKey<CalendarState> calendarKey = GlobalKey();

//  點擊之後拿值
  void _handleNewDate(date) {
    setState(() {
      _signIn = null;
      _selectedDay = date;
      _getStudentSignIn();
      _selectedEvents = _events[_selectedDay] ?? [];
    });
    print(_selectedEvents);
  }

//  彈窗選擇日期
  void _showDatePicker() {
    DatePicker.showDatePicker(
      context,
      pickerTheme: DateTimePickerTheme(
        backgroundColor: Color(0xfff9f9f9),
        showTitle: _showTitle,
        confirm: Text("完成",
            style: TextStyle(
                color: Color(0xff007AFF),
                fontSize: ScreenUtil().setSp(15),
                fontWeight: FontWeight.w500)),
        cancel: Text(''),
      ),
      minDateTime: DateTime.parse(MIN_DATETIME),
      maxDateTime: DateTime.parse(MAX_DATETIME),
      initialDateTime: _dateTime,
      dateFormat: _format,
      locale: _locale,
      onConfirm: (dateTime, List<int> index) {
        setState(() {
          _dateTime = dateTime;
          this.dateTime = formatDate(dateTime, [yyyy, '-', mm]);
          calendarKey.currentState.setToDate(dateTime, isWeek: false);
        });
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    final width = MediaQuery.of(context).size.width;
    return Scaffold(
      appBar: MyAppBar(title: "出勤记录",),
      body: Container(
          color: Colors.white,
          child: SingleChildScrollView(
            child: Column(
              children: <Widget>[
                Container(
                  decoration: new BoxDecoration(boxShadow: [
                    BoxShadow(
                      offset: Offset(0.0, 16.0),
                      color: Color(0xfffefeff),
                      blurRadius: 25.0,
                      spreadRadius: -9.0,
                    ),
                  ]),
                  child: Container(
                      width: width * 0.95,
                      padding: EdgeInsets.only(
                        left: 20,
                        right: 20,
                      ),
                      margin: const EdgeInsets.only(
                        left: 15,
                        right: 15,
                      ),
                      decoration:
                      BoxDecoration(color: Colors.white, boxShadow: [
                        BoxShadow(
                          offset: Offset(0.0, 16.0),
                          color: Color(0xfffefeff),
                          blurRadius: 25.0,
                          spreadRadius: -9.0,
                        ),
                      ]),
                      child: Column(
                        children: <Widget>[
                          Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: <Widget>[
                              RichText(
                                text: TextSpan(
                                  children: [
                                    TextSpan(
                                      text: dateTime,
                                      style: TextStyle(
                                          color: Color(0xff144d7c),
                                          fontWeight: FontWeight.w600,
                                          fontSize: 20),
                                    ),
                                  ],
                                ),
                              ),
                              IconButton(
                                icon: Icon(Icons.keyboard_arrow_down),
                                color: Color(0xff144d7c),
                                onPressed: _showDatePicker,
                              )
                            ],
                          ),
                          Calendar(
                            key: calendarKey,
                            events: _events,
                            onRangeSelected: (range) {
                              print("${range.from}, ${range.to}");
                              setState(() {dateTime = formatDate(range.from, [yyyy, '年', mm, '月']);});
                            },
                            onDateSelected: (date) => _handleNewDate(date),
                            isExpandable: true,
                            isDisableSwipeUpAndDow: true,
                            showTodayIcon: true,
                          ),
                        ],
                      )),
                ),
                punchComponent(width),
              ],
            ),
          )),
    );
  }

  Widget punchComponent(width) {
    return Container(
      width: width,
      height: width * 0.5,
      padding: EdgeInsets.only(bottom: 20, top: 10),
      decoration: new BoxDecoration(boxShadow: [
        BoxShadow(
          offset: Offset(0.0, 6.0),
          color: Color(0xffebeef2),
          blurRadius: 25.0,
          spreadRadius: -9.0,
        ),
      ]),
      child: Container(
          width: width * 0.95,
          padding: EdgeInsets.only(
            left: 20,
            right: 20,
          ),
          margin: const EdgeInsets.only(
            left: 15,
            right: 15,
          ),
          decoration: BoxDecoration(
              borderRadius: BorderRadius.all(Radius.circular(20)),
              color: Colors.white,
              boxShadow: [
                BoxShadow(
                  offset: Offset(0.0, 6.0),
                  color: Color(0xffebeef2),
                  blurRadius: 2.0,
                  spreadRadius: -9.0,
                ),
              ]),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              _signIn != null
                  ? punchItem(
                  '到達時間', _signIn != null ? _signIn.checkInAt : null)
                  : punchItemNot('到達時間'),
              Container(
                width: width * 0.95,
                height: 1,
                color: Color(0xffebebeb),
              ),
              _signIn != null
                  ? punchItem(
                  '離開時間', _signIn != null ? _signIn.checkOutAt : null)
                  : punchItemNot('離開時間'),
            ],
          )),
    );
  }

  Widget punchItem(String title, DateTime time) {
    return Container(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          new Expanded(
            child: Center(
              child: Text(
                title,
                style: TextStyle(
                  color: Color(0xff144d7c),
                  fontSize: ScreenUtil().setSp(14),
                  fontFamily: "SemiBold",
                ),
              ),
            ),
            flex: 1,
          ),
          new Expanded(
            child: Center(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Text(
                    time == null ? '--' : time.hour.toString(),
                    style: TextStyle(
                        color: Color(0xff2d7fc7),
                        fontSize: ScreenUtil().setSp(48),
                        fontWeight: FontWeight.w700),
                  ),
                  Text(
                    ":",
                    style: TextStyle(
                        color: Color(0xff154d7c),
                        fontSize: ScreenUtil().setSp(48),
                        fontWeight: FontWeight.w700),
                  ),
                  Text(
                    time == null ? '--' : time.minute.toString(),
                    style: TextStyle(
                        color: Color(0xff2d7fc7),
                        fontSize: ScreenUtil().setSp(48),
                        fontWeight: FontWeight.w700),
                  ),
                  Padding(
                    padding: EdgeInsets.only(left: 15),
                  ),
                  time != null
                      ? Text(
                    formatDate(time.toLocal(), [am]),
                    style: TextStyle(
                        color: Color(0xff154d7c),
                        fontSize: ScreenUtil().setSp(36),
                        fontWeight: FontWeight.w600),
                  )
                      : Text('')
                ],
              ),
            ),
            flex: 3,
          ),
        ],
      ),
    );
  }

  Widget punchItemNot(String title) {
    return Container(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          new Expanded(
            child: Center(
              child: Text(
                title,
                style: TextStyle(
                  color: Color(0xff144d7c),
                  fontSize: ScreenUtil().setSp(14),
                  fontFamily: "SemiBold",
                ),
              ),
            ),
            flex: 1,
          ),
          new Expanded(
            child: Center(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Text(
                    '--',
                    style: TextStyle(
                        color: Color(0xff2d7fc7),
                        fontSize: ScreenUtil().setSp(48),
                        fontWeight: FontWeight.w700),
                  ),
                  Text(
                    ":",
                    style: TextStyle(
                        color: Color(0xff154d7c),
                        fontSize: ScreenUtil().setSp(48),
                        fontWeight: FontWeight.w700),
                  ),
                  Text(
                    '--',
                    style: TextStyle(
                        color: Color(0xff2d7fc7),
                        fontSize: ScreenUtil().setSp(48),
                        fontWeight: FontWeight.w700),
                  ),
                  Padding(
                    padding: EdgeInsets.only(left: 15),
                  ),
                ],
              ),
            ),
            flex: 3,
          ),
        ],
      ),
    );
  }
}
